package com.bailan.foreat.interceptors;


import com.bailan.foreat.utils.CookieUtils;
import com.bailan.foreat.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        try {
            JwtUtils.getAccount(userTokenFromCookie);
        } catch (Exception e) {
            //判断请求是否是ajax请求
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                //为false，token验证异常。不予服务
                System.out.println("已拦截未登录的请求");
                response.setStatus(401);
            } else {
                System.out.println("下面是拦截地址/common/tologin");
//                request.getRequestDispatcher("/freshFrame").forward(request, response);
                request.getRequestDispatcher("/common/tologin").forward(request, response);
//                response.sendRedirect("/freshFrame");
            }
            return false;
        }
        return true;
    }
}
